package com.clickpaas.governmentcloud.utils.portalutils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 方延杰
 * @version 1.0
 * @since 2020/9/24 2:49 下午
 */

public class JsonUtils {

    public static JSONObject jsonStrToJson(String data) {

        if (data != null) {
            try {
                return JSON.parseObject(data);
            } catch (Exception ignored) {
            }
        }

        return null;

    }

    public static JSONObject objToJson(Object data) {

        if (data != null) {
            try {
                String s = JSON.toJSONString(data);
                return JSON.parseObject(s);
            } catch (Exception ignored) {
            }
        }

        return null;

    }

    /**
     * 对象转数组
     * @param obj
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> List<T> castList(Object obj, Class<T> clazz) {
        List<T> result = new ArrayList<T>();
        if(obj instanceof List<?>) {
            for (Object o : (List<?>) obj) {
                result.add(clazz.cast(o));
            }
            return result;
        }
        return null;
    }

}
